<template>
  <el-card>
    <el-row :gutter="20">
      <el-col :span="5" :offset="0">
        <el-input
          v-model="queryForm.userName"
          placeholder="请输入用户姓名"
          size="default"
          clearable
        >
        </el-input>
      </el-col>
      <el-button
        type="primary"
        size="default"
        :icon="Search"
        @click="initTableList()"
        >搜索</el-button
      >
      <el-button
        type="warning"
        size="default"
        :icon="Delete"
        @click="clearInput"
        >清空</el-button
      >
    </el-row>
  </el-card>
  <el-card class="body">
    <el-row :gutter="20">
      <el-col :span="12" :offset="0">
        <el-button type="primary" size="default" @click="handleDialogValue()">
          添加用户
        </el-button>
        <el-button type="danger" size="default" @click="deleteUsers">
          批量删除
        </el-button>
      </el-col>
    </el-row>
    <!-- @selection-change="handleSelectionChange" -->
    <el-table
      class="table"
      ref="multipleTableRef"
      :data="tableData"
      style="width: 100%"
      border
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40" />
      <!-- <el-table-column
        label="序号"
        type="index"
        width="55"
        align="center"
      ></el-table-column> -->
      <el-table-column
        v-for="(item, index) in options"
        :key="index"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
        align="center"
      >
        <template v-slot="{ row }" v-if="item.prop === 'status'">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            inline-prompt
            active-text="开"
            inactive-text="关"
            @change="changeState(row)"
          />
        </template>

        <template #default="{ row }" v-else-if="item.prop === 'manipulate'">
          <el-button
            type="info"
            size="small"
            :icon="User"
            title="分配角色"
            @click="handleRoleDialog(row)"
          ></el-button>
          <el-button
            type="warning"
            size="small"
            :icon="Edit"
            title="编辑"
            @click="handleDialogValue(row)"
          ></el-button>
          <el-popconfirm
            title="Are you sure to delete this?"
            @confirm="confirmEvent(row)"
          >
            <template #reference>
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                title="删除"
              ></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:currentPage="queryForm.pageNo"
      v-model:page-size="queryForm.pageSize"
      :page-sizes="[2, 10, 20]"
      layout=" prev, pager, next, jumper,->, sizes,total"
      :total="total"
      style="text-align: right"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>
  <Dialog
    v-model="dialogVisible"
    v-if="dialogVisible"
    :dialogTitle="dialogTitle"
    :dialogTableValue="dialogTableValue"
    @initTableList="initTableList"
  />
  <RoleDialog
    v-model="roleDialogVisible"
    v-if="roleDialogVisible"
    :roleDialogUser="roleDialogUser"
    :roleNameList="roleNameList"
    :userRoleList="userRoleList"
    @initTableList="initTableList"
  />
</template>

<script setup>
import { Delete, Search, Edit, User } from '@element-plus/icons-vue'
import { options } from './options'
import { reactive, ref } from 'vue'
import {
  getUserListByPageInfo,
  addOrModifyUser,
  deleteUserByIds,
  getAllRoleList,
  getUserRoleListById
} from '@/api/authority.js'
import cloneDeep from 'lodash/cloneDeep'
import { ElMessage, ElMessageBox } from 'element-plus'
import Dialog from './components/dialog.vue'
import RoleDialog from './components/roleDialog.vue'
import { isNull } from '@/utils/filters.js'
import { handleTokenExpire } from '@/utils/handleTokenExpire.js'

const dialogTitle = ref('')
const dialogTableValue = ref({})
const loading = ref(true)
const roleDialogVisible = ref(false)
const roleDialogUser = ref('')
const userRoleList = ref([])
const roleNameList = ref([])

const queryFormInit = () => {
  return {
    userName: '',
    pageNo: 1,
    pageSize: 2
  }
}
const queryForm = reactive(queryFormInit())

const total = ref(0)
const tableData = ref([])

const dialogVisible = ref(false)

const initTableList = async () => {
  try {
    const res = await getUserListByPageInfo(queryForm)
    const { records } = res.data
    // console.log(records)
    tableData.value = records
    total.value = res.data.total
    loading.value = false
  } catch (error) {
    handleTokenExpire(error)
  }
}

initTableList()

const handleSizeChange = (val) => {
  queryForm.pageSize = val
  queryForm.pageNo = 1
  initTableList(queryForm)
}

const handleCurrentChange = (val) => {
  queryForm.pageNo = val
  initTableList(queryForm)
}

const clearInput = () => {
  Object.assign(queryForm, queryFormInit())
  initTableList()
}

const changeState = async (row) => {
  try {
    await addOrModifyUser(row)
    initTableList()
    ElMessage({
      type: 'success',
      message: '更新成功',
      duration: 1500
    })
    initTableList()
  } catch (error) {
    ElMessage({
      type: 'error',
      message: error.message,
      duration: 1500
    })
  }
}

const handleDialogValue = (row) => {
  // 判断row是否为空 空对象  空数组
  if (isNull(row)) {
    dialogTitle.value = '添加用户'
  } else {
    dialogTitle.value = '编辑用户'
    // 此处需要深拷贝
    dialogTableValue.value = JSON.parse(JSON.stringify(row))
  }
  dialogVisible.value = true
}

// 单个删除
const confirmEvent = async (row) => {
  const userIds = []
  userIds.push(JSON.parse(JSON.stringify(row.id)))
  try {
    await deleteUserByIds(userIds)
    ElMessage({
      type: 'success',
      message: '删除成功',
      duration: 1500
    })
    initTableList()
  } catch (error) {
    ElMessage({
      type: 'error',
      message: error,
      duration: 1500
    })
  }
}

const multipleSelection = ref([])

// 多个删除
const deleteUsers = () => {
  ElMessageBox.confirm(
    'proxy will permanently delete the file. Continue?',
    'Warning',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning'
    }
  )
    .then(async () => {
      // 处理删除多个用户
      const userIds = JSON.parse(JSON.stringify(multipleSelection.value))
      await deleteUserByIds(userIds)
      ElMessage({
        type: 'success',
        message: 'Delete completed',
        duration: 1500
      })
      initTableList()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
        duration: 1500
      })
    })
}
// 获取多个选中userIds
const handleSelectionChange = (rows) => {
  const arr = JSON.parse(JSON.stringify(rows))
  const userIds = arr.map((item) => item.id)
  multipleSelection.value = userIds
}

const handleRoleDialog = async (row) => {
  // console.log(row)
  try {
    // 获取用户的角色ids
    const res1 = await getUserRoleListById({ userId: row.id })
    if (res1.code === 200) {
      const userRoleIds = res1.data.map((item) => item.roleId)
      userRoleList.value = userRoleIds
      // console.log(userRoleIds) //["1"]
    } else {
      return false
    }

    // 获取角色列表
    const res = await getAllRoleList()
    // console.log(res)// 200
    if (res.code === 200) {
      const allRoleList = res.data
      const finalRoleNameList = allRoleList.map((item) => {
        const role = {}
        role.id = item.id
        role.roleName = item.roleName
        role.roleRemark = item.roleRemark
        return role
      })
      roleNameList.value = finalRoleNameList
    } else {
      return false
    }
    roleDialogVisible.value = true
    roleDialogUser.value = JSON.parse(JSON.stringify(row))
    // console.log(finalRoleNameList)[{…}, {…}, {…}]
  } catch (error) {
    ElMessage({
      type: 'error',
      duration: 1500,
      message: error
    })
  }
}
</script>

<style lang="scss" scoped>
.body {
  box-sizing: border-box;
  margin-top: 20px;
}
.table {
  box-sizing: border-box;
  margin: 20px 0px;
}
</style>
